package net.tngou.tpage.http;



import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;



import org.apache.commons.lang3.time.DateUtils;

import net.tngou.tpage.cache.CacheEngine;
import net.tngou.tpage.cache.EhCacheEngine;
import net.tngou.tpage.pojo.Login;
import net.tngou.tpage.pojo.User;
import net.tngou.tpage.util.OAuthUtil;
import net.tngou.tpage.util.StringUtil;






/**
 * 这里我们主要用的的ehcache来代替传统的session
 * @author 陈磊
 *
 */

public class SessionContext  implements HttpSession {

	
	private static CacheEngine cacheEngine =new  EhCacheEngine().getInstance();
	private final String fullyQualifiedName = "session";
	@Override
	public void setAttribute(String name, Object value)
	{
		
		cacheEngine.add(fullyQualifiedName, name, value);
	}

	@Override
	public void removeAttribute(String name)
	{
		cacheEngine.remove(fullyQualifiedName, name);
	}

	@Override
	public Object getAttribute(String name)
	{
		return cacheEngine.get(fullyQualifiedName, name);
	}

	@Override
	public User getUser(String userid) {
		
		if(StringUtil.isBlank(userid))return null;		
		User user = (User) getAttribute(userid);  //缓存里面取得user
		if(user==null) //如果session缓存里面没有，
		{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("access_token", userid);
			Login bean = new Login();
			Login login = bean.get(map );
			if(login!=null)
			{
				user=new User().get(login.getUser());
				Timestamp timestamp = new  Timestamp(DateUtils.addDays(new Date(), 30).getTime());
				map.clear();
				map.put("expiredtime", timestamp);
				bean.update(map, login.getId());
				setUser(user);//设置
				
				
				
				
			}
		}
		
		return user;
	}

	@Override
	public void setUser(User user) 
	{
		String access_token=OAuthUtil.Access_token(user.getAccount(),user.getPassword());
		user.setAccess_token(access_token);
		setAttribute(access_token, user);
		
	}

	@Override
	public void deleteUser(String userid) {
		removeAttribute(userid);
		
	}


	
	

}
